package com.qjjbmt.zhq_blog_admin.controller;

import com.qjjbmt.zhq_blog_admin.pojo.Blog;
import com.qjjbmt.zhq_blog_admin.service.impl.BlogServiceImpl;
import com.qjjbmt.zhq_blog_admin.service.impl.UserServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.time.LocalDateTime;
import java.util.Collection;

@Controller
public class BlogController {

    UserServiceImpl userService;
    BlogServiceImpl blogService;

    public BlogController(BlogServiceImpl blogService, UserServiceImpl userService){
        this.blogService = blogService;
        this.userService = userService;
    }

    /*
    查询所有博客
     */
    @RequestMapping("/blogs")
    public String list(Model model){
        Collection<Blog> blogs = blogService.list();
        model.addAttribute("blogs",blogs);
        return "blog/blog_list";
    }

    /*
    跳转到添加页面
     */
    @GetMapping("/addBlog")
    public String toAddBlogPage(Model model){
        model.addAttribute("users",userService.list());
        return "blog/add";
    }

    /*
   添加博客，然后刷新列表
    */
    @PostMapping("/addBlog")
    public String addBlog(Blog blog){
        LocalDateTime dateTime = LocalDateTime.now();
        blog.setCreateTime(dateTime);
        blog.setUpdateTime(dateTime);

        blogService.save(blog);
        return "redirect:/blogs";
    }

    /*
    根据id查询博客，然后跳转到修改页面并展示
     */
    @GetMapping("/blog/{id}")
    public String toUpdateBlogPage(@PathVariable("id")Integer id, Model model){
        //查出原来的数据
        model.addAttribute("blog",blogService.getById(id));
        model.addAttribute("users",userService.list());
        return "blog/update";
    }

    /*
    保存管理员的修改
     */
    @RequestMapping("/updateBlog")
    public String updateBlog(Blog blog){
        LocalDateTime localDateTime = LocalDateTime.now();
        blog.setUpdateTime(localDateTime);
        blogService.updateById(blog);
        return "redirect:/blogs";
    }

    /*
    根据id删除评论，然后刷新列表,并删除此评论的相关回复
     */
    @GetMapping("/delBlog/{id}")
    public String deleteBlog(@PathVariable("id") Integer id){
        blogService.removeById(id);
        return "redirect:/comments";
    }
}
